package com.edee.bigday.commodity.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.edee.bigday.commodity.dao.BrandDao;
import com.edee.bigday.commodity.entity.BrandEntity;
import com.edee.bigday.commodity.service.BrandService;
import com.edee.bigday.commodity.service.CategoryBrandRelationService;
import com.edee.common.utils.PageUtils;
import com.edee.common.utils.Query;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;


@Service("brandService")
public class BrandServiceImpl extends ServiceImpl<BrandDao, BrandEntity> implements BrandService {

    @Autowired
    CategoryBrandRelationService categoryBrandRelationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        //获取key，进行模糊查询：
        String key = (String) params.get("key");
        QueryWrapper<BrandEntity> queryWrapper = new QueryWrapper<>();
        if(!StringUtils.isEmpty(key)){
            queryWrapper.eq("brand_id",key).or().like("name",key);
        }
        IPage<BrandEntity> page = this.page(
                new Query<BrandEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    /**
     * 级联更新品牌名称
     * @param brand
     */
    @Transactional //开启事务
    @Override
    public void updateDetail(BrandEntity brand) {
        //保证冗余字段的数据一致：
        this.updateById(brand); //先更新当前表数据
        if(!StringUtils.isEmpty(brand.getName())){
            //如果名称发生了变化，需要同步更新其它关联表中的名称：
            categoryBrandRelationService.updateBrand(brand.getBrandId(),brand.getName());
            //TODO 同时更新其它关联表中的名称：
        }
    }

    @Cacheable(value = "brands",key = "'brandsinfo:'+#root.args[0]")
    @Override
    public List<BrandEntity> getBrandsById(List<Long> brandIds) {
        List<BrandEntity> brandEntities = baseMapper.selectList(new QueryWrapper<BrandEntity>().in("brand_id", brandIds));
        return brandEntities;
        //或者直接：
        //return baseMapper.selectList(new QueryWrapper<BrandEntity>().in("brand_id", brandIds));
    }

}